package accesslog

import (
	"encoding/json"
	"gofire"
	"log"
)

type MiddlewareBuilder struct {
	logFunc func(accessLog string)
}

func (b *MiddlewareBuilder) LogFunc(logFunc func(accessLog string)) *MiddlewareBuilder {
	b.logFunc = logFunc
	return b
}

func NewBuilder() *MiddlewareBuilder {
	return &MiddlewareBuilder{
		logFunc: func(accessLog string) {
			log.Println(accessLog)
		},
	}
}

func (b *MiddlewareBuilder) Build() gofire.Middleware {
	return func(handleFunc gofire.HandleFunc) gofire.HandleFunc {
		return func(ctx *gofire.Context) error {
			defer func() {
				l := accessLog{
					Host:       ctx.Request.Host,
					Path:       ctx.Path(),
					HTTPMethod: ctx.Method(),
				}
				val, _ := json.Marshal(l)
				b.logFunc(string(val))
			}()
			return handleFunc(ctx)
		}
	}
}

type accessLog struct {
	Host       string
	HTTPMethod string `json:"http_method"`
	Path       string
}
